package cn.tedu.sp06.fb;

import cn.tedu.sp01.util.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

@Component
@Slf4j
public class ItemFB implements FallbackProvider {
    /**
     * @return 设置针对哪个后台服务进行降级
     * <br>item-service : 只针对商品服务进行降级
     * <br>"*" : 对所以服务都应用当前降级类
     * <br>null : 对所以服务都应用当前降级类
     */
    @Override
    public String getRoute() {
        return "item-service";
    }

    /**
     * 向客户端发回的响应降级
     * 错误提示/缓存数据/根据业务逻辑返回任意数据
     * @param route
     * @param cause
     * @return
     */
    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return new ClientHttpResponse() {
            /**
             * HttpStatus 封装信息
             * @return 状态码 和 文本信息
             * @throws IOException
             */
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.INTERNAL_SERVER_ERROR;
            }

            /**
             * getRawStatusCode
             * @return 状态码
             * @throws IOException
             */
            @Override
            public int getRawStatusCode() throws IOException {
                return HttpStatus.INTERNAL_SERVER_ERROR.value();
            }

            /**
             * getStatusText
             * @return 文本信息
             * @throws IOException
             */
            @Override
            public String getStatusText() throws IOException {
                return HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase();
            }

            /**
             * 用来关闭下面的流,BAIS 虚拟机中读取byte[]数组的流对象,不占用底层系统资源,不需要关闭
             */
            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                String jsonStr = JsonResult
                        .err()
                        .code(500)
                        .msg("后台服务出错,请稍后重试")
                        .toString();
                return new ByteArrayInputStream(jsonStr.getBytes(StandardCharsets.UTF_8));
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders httpHeaders = new HttpHeaders();
                httpHeaders.add("Content-Type","application/json;charset=UTF-8");
                return httpHeaders;
            }
        };
    }
}
